#include "TrayConfigsDoc.h"

void TrayConfigsDoc::fromJson(const QJsonObject& json, QStringList& errorList)
{
    BaseDocument::fromJson(json, errorList);

    QJsonArray jsonItems;

    jsonItems = json.value("data").toArray();
    m_data->clear();
    for (int i = 0; i < jsonItems.size(); ++i) {
        shared_ptr<TrayConfig> item = make_shared<TrayConfig>();
        item->fromJson(jsonItems[i].toObject(), errorList);
        m_data->insert_or_assign(item->trayNo, item);
    }
}

QJsonObject TrayConfigsDoc::toJson() const
{
    QJsonObject json = BaseDocument::toJson();

    QJsonArray items;
    items = QJsonArray();

    int index = 0;
    for (auto it = m_data->begin(); it != m_data->end(); ++it, ++index) {
        items.append(it->second->toJson());
    }

    json.insert("data", items);

    return json;
}

shared_ptr<TrayConfig> TrayConfigsDoc::get(const QString& key)
{
    auto it = m_data->find(key);
    if (it != m_data->end()) {
        return it->second;
    }

    shared_ptr<TrayConfig> config = make_shared<TrayConfig>();
    return config;
}

void TrayConfigsDoc::set(shared_ptr<TrayConfig> value)
{
    m_data->insert_or_assign(value->trayNo, value);
}
